//
//  MWMineController.m
//  XiRan-iOS
//
//  Created by Richfit on 2019/10/10.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWMineController.h"
#import "MWHomepageController.h"
#import "MWMessageController.h"
#import "MWMineCollectionController.h"
#import "MWLanguageSwitchController.h"
#import "MWBrandSwitchController.h"
#import "MWFormulaController.h"
#import "MWAboutController.h"
#import "MWNavigationController.h"
#import "MWPasswordLoginController.h"

#import "MWMineHeaderView.h"
#import "MWMineFooterView.h"
#import "MWMinePriceCell.h"
#import "MWMineCommonCell.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/PHPhotoLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>

#import "MWMineModel.h"

@interface MWMineController () <UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong) MWMineHeaderView *headerView;
@property(nonatomic, strong) MWMineFooterView *footerView;
@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, strong) UIView *logoutView;
@property(nonatomic, strong) UIView *topView;
@property(nonatomic, strong) UIImageView *backgroundIV;
@property(nonatomic, strong) UIButton *avatarBtn;
@property(nonatomic, strong) UIButton *nameBtn;
@property(nonatomic, strong) UILabel *descLB;
@property(nonatomic, strong) UIButton *loginBtn;

@property(nonatomic, strong) NSMutableArray *modelArray;

@property(nonatomic, strong) MBProgressHUD *hud;

@end

@implementation MWMineController

- (instancetype)init {
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleLoginResultNotification:) name:kLoginResultNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleLoginOverdueNotification:) name:kLoginOverdueNotification object:nil];

        // 不是访客
        if ([MWUserManager manager].user.mid != 2) {
             [self loadUserInfo];
        }
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadVisitorInfoNotification) name:@"CloseTheAccountNotification" object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MWHexColor(@"#ECF9FF");
    [self setupPageSubviews];
    
    if ([MWUserManager manager].user.mid == 2) {
        _logoutView.hidden = NO;
        _tableView.hidden = YES;
    } else {
        _logoutView.hidden = YES;
        _tableView.hidden = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [_tableView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kLoginResultNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)loginAction:(UIButton *)sender {
    MWPasswordLoginController *controller = [[MWPasswordLoginController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)logout {
    [self logoutWithMobile:[MWUserManager manager].user.mobile];
}

- (void)handleLoginResultNotification:(NSNotification *)notification {
    [self loadUserInfo];
}

- (void)handleLoginOverdueNotification:(NSNotification *)notification {
    [MWUserManager manager].user = nil;
    [[MWUserManager manager] clearUser];
    [self loadVisitorInfo];
}


#pragma mark - 获取个人信息
- (void)loadUserInfo {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kUserInfoUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            NSDictionary *dataDic = [dic objectForKey:@"data"];
            MWUser *user = [MWUser mj_objectWithKeyValues:dataDic];
            [MWUserManager manager].user.avatar = user.avatar;
            [MWUserManager manager].user.nickname = user.nickname;
            [MWUserManager manager].user.mobile = user.mobile;
            [MWUserManager manager].user.email = user.email;
            [MWUserManager manager].user.is_show_money = user.is_show_money;
            [MWUserManager manager].user.is_show_formula = user.is_show_formula;
//            [MWUserManager manager].user.language = user.language;
            [MWUserManager manager].user.change_app = user.change_app;
            
            [self makeCellData];
    
            weakSelf.logoutView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            [weakSelf.tableView reloadData];
            
        } else {
            
        }
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - 是否显示价格
- (void)showPriceWithType:(NSString *)type {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:type forKey:@"type"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    _hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    _hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kMineShowPriceUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        
        if (code == 1) {
            NSDictionary *dataDic = [dic objectForKey:@"data"];
            [MWUserManager manager].user.is_show_money = [[dataDic objectForKey:@"is_show_money"] integerValue];
            [[NSNotificationCenter defaultCenter] postNotificationName:kSwitchPriceNotification object:nil];
        }
        
        weakSelf.hud.mode = MBProgressHUDModeText;
        weakSelf.hud.label.text = msg;
        [weakSelf.hud hideAnimated:YES afterDelay:2];
        
    } failure:^(NSError *error) {
        [weakSelf.hud hideAnimated:YES];
    }];
}

#pragma mark - 注销登录
- (void)logoutWithMobile:(NSString *)mobile {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:mobile forKey:@"mobile"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    _hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    _hud.label.text = @"";
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kLogoutUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            [MWUserManager manager].user = nil;
            [[MWUserManager manager] clearUser];
            
            [self loadVisitorInfo];
           
        } else {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = msg;
            [weakSelf.hud hideAnimated:YES afterDelay:2];
        }
        
    } failure:^(NSError *error) {
        [weakSelf.hud hideAnimated:YES];
    }];
}

#pragma mark - 未登录时访客需要
- (void)loadVisitorInfoNotification
{
    _hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    _hud.label.text = @"";
    [self loadVisitorInfo];
}

- (void)loadVisitorInfo {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kVsitorLoginUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        [weakSelf.hud hideAnimated:YES];
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        if (code == 1) {
            NSDictionary *dataDic = [dic objectForKey:@"data"];
            MWUser *user = [MWUser mj_objectWithKeyValues:[dataDic objectForKey:@"userinfo"]];
            [MWUserManager manager].user = user;
            
            weakSelf.logoutView.hidden = NO;
            weakSelf.tableView.hidden = YES;
        }
       
    } failure:^(NSError *error) {
        [weakSelf.hud hideAnimated:YES];
    }];
}

#pragma mark - UITableViewDataSource && UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 300.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 100.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (!_headerView) {
        _headerView = [[MWMineHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 212)];
    }
    
    MWWeakSelf
    _headerView.block = ^(NSInteger position) {
        if (position  == 0) {
            
        } else if (position  == 1) {
            MWHomepageController *controller = [[MWHomepageController alloc] init];
            [weakSelf.navigationController pushViewController:controller animated:YES];
            
        } else if (position  == 2) {
            MWMessageController *controller = [[MWMessageController alloc] init];
            [weakSelf.navigationController pushViewController:controller animated:YES];
            
        } else if (position  == 3) {
            MWMineCollectionController *controller = [[MWMineCollectionController alloc] init];
            [weakSelf.navigationController pushViewController:controller animated:YES];
            
        } else if (position  == 4) {
            MWLanguageSwitchController *controller = [[MWLanguageSwitchController alloc] init];
            [weakSelf.navigationController pushViewController:controller animated:YES];
            
        } else if (position  == 5) {
            MWAboutController *controller = [[MWAboutController alloc] init];
            [weakSelf.navigationController pushViewController:controller animated:YES];
        }
    };
    
    [_headerView.homepageBtn setTitle:[[MWConfigManager manager] objectForKey:@"personal" defaultValue:@"个人主页"] forState:UIControlStateNormal];
    [_headerView.homepageBtn setIconInRightWithSpacing:10];
    
    MWUser *user = [MWUserManager manager].user;
    _headerView.avatarUrl = user.avatar;
    if (user.nickname && user.nickname.length) {
        _headerView.nameLB.text = user.nickname;
    }
    if (user.mobile && user.mobile.length) {
        _headerView.descLB.text = user.mobile;
    }
    
    return _headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (!_footerView) {
        _footerView = [[MWMineFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    }
    MWWeakSelf
    _footerView.block = ^{
        [weakSelf logout];
    };
    
    return _footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MWMineModel *model = self.modelArray[indexPath.row];
    if ([model.image isEqualToString:@"xr_mine_price"]) {
        static NSString *identifier = @"MWMinePriceCell";
        MWMinePriceCell *priceCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!priceCell) {
            priceCell = [[MWMinePriceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            priceCell.selectionStyle = UITableViewCellSelectionStyleNone;
            priceCell.backgroundColor = MWHexColor(@"#ECF9FF");
        }
        
        priceCell.block = ^(BOOL isOn) {
            if (isOn) {
                [self showPriceWithType:@"1"];
            } else {
                [self showPriceWithType:@"0"];
            }
        };
        
        priceCell.iconIV.image = [UIImage imageNamed:model.image];
        priceCell.titleLB.text = model.title;
        
        if ([MWUserManager manager].user.is_show_money == 1) {
            priceCell.switchBtn.on = YES;
        } else {
            priceCell.switchBtn.on = NO;
        }
        
        return priceCell;
        
    } else {
        static NSString *identifier = @"MWMineCommonCell";
        MWMineCommonCell *mineCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!mineCell) {
            mineCell = [[MWMineCommonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            mineCell.selectionStyle = UITableViewCellSelectionStyleNone;
            mineCell.backgroundColor = MWHexColor(@"#ECF9FF");
        }
        mineCell.iconIV.image = [UIImage imageNamed:model.image];
        mineCell.titleLB.text = model.title;
        
        return mineCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MWMineModel *model = self.modelArray[indexPath.row];
    if ([model.image isEqualToString:@"xr_mine_message"]) {
        MWMessageController *controller = [[MWMessageController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
        
    } else if ([model.image isEqualToString:@"xr_mine_collect"]) {
        MWMineCollectionController *controller = [[MWMineCollectionController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
        
    } else if ([model.image isEqualToString:@"xr_mine_language"]) {
        MWLanguageSwitchController *controller = [[MWLanguageSwitchController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
        
    } else if ([model.image isEqualToString:@"xr_mine_brand"]) {
        MWBrandSwitchController *controller = [[MWBrandSwitchController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
        
    } else if ([model.image isEqualToString:@"xr_mine_formula"]) {
        MWFormulaController *controller = [[MWFormulaController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
        
    } else if ([model.image isEqualToString:@"xr_mine_about"]) {
        MWAboutController *controller = [[MWAboutController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    }
}

- (NSMutableArray *)modelArray {
    if (!_modelArray) {
        _modelArray = [[NSMutableArray alloc] init];
    }
    return _modelArray;
}

- (void)makeCellData {
    [self.modelArray removeAllObjects];

    if ([MWUserManager manager].user.is_show_formula == 1) {
        MWMineModel *formulaModel = [[MWMineModel alloc] init];
        formulaModel.image = @"xr_mine_formula";
        formulaModel.title = [[MWConfigManager manager] objectForKey:@"gongshibaojia" defaultValue:@"报价"];
        [self.modelArray addObject:formulaModel];
    }
    
    if ([MWUserManager manager].user.change_app == 1) {
        MWMineModel *brandModel = [[MWMineModel alloc] init];
        brandModel.image = @"xr_mine_brand";
        brandModel.title = [[MWConfigManager manager] objectForKey:@"brand_change" defaultValue:@"品牌切换"];
        [self.modelArray addObject:brandModel];
    }
   

    if ([MWUserManager manager].user.level == 1) {
        MWMineModel *priceModel = [[MWMineModel alloc] init];
        priceModel.image = @"xr_mine_price";
        priceModel.title = [[MWConfigManager manager] objectForKey:@"show_price" defaultValue:@"显示价格"];
        [self.modelArray addObject:priceModel];
    }

}

- (void)setupPageSubviews {
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = MWHexColor(@"#ECF9FF");
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    _logoutView = [[UIView alloc] init];
    [self.view addSubview:_logoutView];
    
    _topView = [[UIView alloc] init];
    [_logoutView addSubview:_topView];
    
    _backgroundIV = [[UIImageView alloc] initWithFrame:CGRectZero];
    _backgroundIV.image = [UIImage imageNamed:@"mine_header_bg"];
    [_topView addSubview:_backgroundIV];
    
    _avatarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _avatarBtn.tag = 0;
    _avatarBtn.layer.cornerRadius = 30;
    _avatarBtn.layer.masksToBounds = YES;
    [_avatarBtn setImage:[UIImage imageNamed:@"infoIcon"] forState:UIControlStateNormal];
    [_avatarBtn setImage:[UIImage imageNamed:@"infoIcon"] forState:UIControlStateHighlighted];
    [_avatarBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:_avatarBtn];
    
    _nameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _nameBtn.titleLabel.font = MWFont(18);
    [_nameBtn setTitle:[[MWConfigManager manager] objectForKey:@"unlogin" defaultValue:@"点击登录"] forState:UIControlStateNormal];
    [_nameBtn setTitleColor:MWHexColor(@"#333333") forState:UIControlStateNormal];
    [_nameBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:_nameBtn];
    
    _descLB = [[UILabel alloc] init];
    _descLB.font = MWFont(12);
    _descLB.textColor = MWHexColor(@"#999999");
    _descLB.text = [[MWConfigManager manager] objectForKey:@"unlogin_desc" defaultValue:@"点击登录查看更多信息"];
    [_topView addSubview:_descLB];
    
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginBtn.layer.cornerRadius = 5;
    _loginBtn.layer.masksToBounds = YES;
    _loginBtn.titleLabel.font = MWFont(14);
    [_loginBtn setTitle:[[MWConfigManager manager] objectForKey:@"login" defaultValue:@"登录"] forState:UIControlStateNormal];
    [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_loginBtn setBackgroundImage:[UIImage imageWithColor:MWHexColor(@"#1E1934")] forState:UIControlStateNormal];
    [_loginBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [_logoutView addSubview:_loginBtn];
    
    [_logoutView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.logoutView);
        make.height.equalTo(@202);
    }];
    
    [_backgroundIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.equalTo(_topView);
        make.width.equalTo(@([UIScreen mainScreen].bounds.size.width * 0.45));
        make.height.equalTo(@([UIScreen mainScreen].bounds.size.width * 0.45 * 447 / 486));
        
    }];
    
    [_avatarBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.topView).offset(16);
        make.bottom.equalTo(self.topView).offset(-66);
        make.width.height.equalTo(@60);
    }];
    
    [_nameBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.avatarBtn.mas_right).offset(15);
        make.bottom.equalTo(self.avatarBtn.mas_centerY).offset(7);
    }];
    
    [_descLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avatarBtn.mas_centerY).offset(4);
        make.left.equalTo(self.avatarBtn.mas_right).offset(15);
    }];
    
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.logoutView).offset(20);
        make.right.equalTo(self.logoutView).offset(-20);
        make.bottom.equalTo(self.logoutView).offset(-200);
        make.height.equalTo(@44);
    }];
}

@end
